#include "kddcup_feat.h"
#include <vector>
#include <algorithm>

using namespace std;

static const int num_items = 6095;
static const int num_users = 2320895;

int user_hit [ num_users ];
int user_last[ num_users ];
int user_sum [ num_users ];
int user_miss[ num_users ];

inline void update( const char *fname, int maxdt ){
    FILE *fi = fopen_check( fname, "r" );
    int uid, ts;
    while( fscanf( fi, "%d%*d%*d%d", &uid, &ts ) == 2 ){
        int last = user_last[ uid ];
        user_last[ uid ] = ts;
        if( last == 0 ){ user_miss[ uid ] ++; continue; }
        if( last == ts ) continue;
        int df = ts - last;
        if( df > maxdt ) {
            user_miss[ uid ] ++; continue;
        }
        user_hit[ uid ] ++;
        user_sum[ uid ] += df;
    }
    fclose( fi );
}

int main( int argc, char* argv[] ) {
	if ( argc < 4 ) {
		printf("Usage: reclog_train.rdx reclog_test.ridx output [maxdt=60]\n");
		return -1;
	}
    int maxdt = 60;
    if( argc > 4 ) maxdt = atoi( argv[4] );
    fill( user_hit , user_hit  + num_users, 0 );
    fill( user_last, user_last + num_users, 0 );
    fill( user_miss, user_miss + num_users, 0 );
    fill( user_sum , user_sum  + num_users, 0 );
    update( argv[1], maxdt );
    update( argv[2], maxdt );
    
    FILE *fo = fopen_check( argv[3], "w" );
    for( int i = 0; i < num_users; i ++ ){
        if( user_hit[i] == 0 ){
            fprintf( fo, "%d\t0\t%d\t%d\n", i, user_hit[i], user_miss[i] );
        }else{
            fprintf( fo, "%d\t%f\t%d\t%d\n", i, ((float)user_sum[i]) / user_hit[i] , user_hit[i], user_miss[i] );
        }        
    }
    fclose( fo );
	return 0;
}
